<template>
  <div class="visitor-index">
    <a-row class="aRow-wrapper" :gutter="12">
      <a-col class="listContent-wrapper" :span="24">
        <div class="title-wrapper-box">
          <top-title :updateTime="false" :content="content"></top-title>
          <!-- <div v-has="'police:add-btn'" class="add-btn cursor" style="position: unset" @click="handelAdd">+ 新增</div> -->
        </div>
        <div class="l-w_content">
          <div class="l-w_c_content">
            <div class="pageInfo">
              <div class="tab-info">
                <a-tabs v-model="activeKey" tab-position="left" @change="handleTabsChange">
                  <a-tab-pane v-for="(item, index) in tabList" :key="index" :tab="item.title"> </a-tab-pane>
                </a-tabs>
              </div>
              <div class="right-content">
                <div v-show="activeKey == 0">
                  <div class="common-title">
                    <div class="icon"></div>
                    <div class="content">身份信息</div>
                  </div>
                  <div class="content-wrapper">
                    <div class="flex">
                      <div class="info-wrap f1">
                        <div class="label common-lable">设备IMEI码</div>
                        <div class="value common-value">{{ wbDeviceBean.imei || '暂无' }}</div>
                      </div>
                      <div class="info-wrap f1">
                        <div class="label common-lable">设备状态</div>
                        <div
                          class="value common-value"
                          :class="wbDeviceBean.onLine == '1' ? 'online-status' : 'offline-status'"
                        >
                          {{ wbDeviceBean.onLine == '1' ? `在线（电量${wbDeviceBean.remainingPower}%）` : '离线' }}
                        </div>
                        <div class="refresh-box">
                          <div class="cursor" @click="handleReset">重启设备</div>
                        </div>
                      </div>
                    </div>
                    <div class="flex">
                      <div class="info-wrap f1">
                        <div class="label common-lable">设备所属医疗机构</div>
                        <div class="value common-value">{{ wbDeviceBean.departmentName || '暂无' }}</div>
                      </div>
                      <div class="info-wrap f1">
                        <div class="label common-lable">设备所属派出所</div>
                        <div class="value common-value">
                          {{ wbDeviceBean.policeAgencyName || '暂无' }}
                        </div>
                      </div>
                    </div>

                    <div class="flex">
                      <div class="info-wrap f1">
                        <div class="label common-lable">设备当前位置</div>
                        <div class="value common-value flex align-center">
                          {{ wbDeviceBean.address || '暂无' }}
                          <img
                            class="location-icon-style"
                            src="@/assets/imgs/location-icon.png"
                            @click="showPosition([wbDeviceBean.lon, wbDeviceBean.lat])"
                          />
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="common-title">
                    <div class="icon"></div>
                    <div class="content">佩戴人员</div>
                  </div>

                  <a-table
                    rowKey="id"
                    class="wearing-table"
                    :columns="columns"
                    :dataSource="wbMentalPatientBean"
                    :pagination="false"
                  >
                    <template slot="action" slot-scope="records">
                      <span class="operation deatil-color" @click="handleChange(records)">更换</span>
                    </template>
                  </a-table>
                  <div class="common-title">
                    <div class="icon"></div>
                    <div class="content">异常数据</div>
                  </div>

                  <abnormal-data :imei="wbDeviceBean.imei"></abnormal-data>

                  <div class="common-title">
                    <div class="icon"></div>
                    <div class="content">生物数据</div>
                  </div>
                  <div class="time-select">
                    <a-radio-group
                      @change="handleTimeTypeChange"
                      v-model="timeType"
                      button-style="solid"
                      class="time-btn-style"
                    >
                      <a-radio-button value="day"> 今日 </a-radio-button>
                      <a-radio-button value="week"> 本周 </a-radio-button>
                      <a-radio-button value="month"> 本月 </a-radio-button>
                    </a-radio-group>
                    <a-range-picker class="time-range" v-model="searchTime" @change="handleTimeRange" />
                  </div>
                  <div>
                    <eCharts :options="heartRateOptions" style="width: 100%; height: 350px" />
                    <eCharts :options="bloodOptions" style="width: 100%; height: 350px" />
                    <eCharts :options="oxgenOptions" style="width: 100%; height: 350px" />
                    <eCharts :options="stepOptions" style="width: 100%; height: 350px" />
                  </div>
                </div>

                <div v-show="activeKey == 1">
                  <a-table
                    rowKey="id"
                    class="wearing-table"
                    :columns="careColumns"
                    :dataSource="deviceHelpInfoNumList"
                    :pagination="false"
                  >
                    <template slot="isResponsible" slot-scope="text, records">
                      <a-switch
                        v-model="records.status"
                        @change="
                          () => {
                            handleChangeResponsible(records)
                          }
                        "
                      />
                    </template>
                    <template slot="action" slot-scope="records">
                      <span class="operation deatil-color" @click="handleChange(records)">更换</span>
                    </template>
                  </a-table>
                </div>

                <div v-show="activeKey == 2" class="right-inner-box">
                  <div class="search-group">
                    <div class="input-wrap">
                      <div class="label">创建时间:</div>
                      <div class="time-item">
                        <start-end-time
                          :times="times"
                          ref="startEndTimeRef"
                          :showTime="{ format: 'HH:mm:ss' }"
                          format="YYYY-MM-DD HH:mm:ss"
                          @timeChange="timeChange"
                          :resetTime="resetTime"
                        ></start-end-time>
                      </div>
                    </div>
                    <div class="btn-wrap">
                      <a-button class="searchBtn" @click="searchQueryTrack()" type="primary"> 搜索 </a-button>
                      <a-button class="resetBtn" @click="searchReset()" type="primary"> 重置 </a-button>
                    </div>
                  </div>
                  <div class="map-wrapper">
                    <div class="button-group">
                      <a-input allowClear class="i-btn" id="tipinput" placeholder="请输入" style="width: 200px" />
                      <a-button class="i-btn"> 实时定位 </a-button>
                      <a-button class="i-btn" @click="handleSettingFence"> 安全围栏设置 </a-button>
                      <a-button class="i-btn"> 清除当前电子围栏 </a-button>
                      <a-button class="i-btn" @click="handleStartMouse"> 鼠标绘制点 </a-button>
                      <a-button class="i-btn" @click="handleClearPoint"> 清除所有点 </a-button>
                      <a-button class="i-btn" @click="handleConfirmPoint"> 4个点确定电子围栏 </a-button>
                    </div>
                    <div id="map-box"></div>
                  </div>
                </div>

                <div v-show="activeKey == 3">
                  <CallLogList />
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    <Add ref="addRef" />
    <SettingFence
      ref="settingFenceRef"
      :point="point"
      :deviceInfo="wbDeviceBean"
      @setFence="onSetFence"
      :fenceInfo="fenceInfo"
    />
    <BindingPersonnel ref="bindingPersonnelRef" @editOk="onEditOk" />
    <map-point ref="mapPointRef" />
  </div>
</template>

<script>
import leftTree from '@/components/leftTree'
import topTitle from '@/components/topTitle'
import list from './modules/list'
import Add from './modules/add'
import { deviceDetails, deviceTrajectory, deviceHelpInfoList, wbHttpFences, deviceinfoSetFance } from '@/api/api'
import CallLogList from './modules/callLogList'
import startEndTime from '@/components/startEndTime'
import * as echarts from 'echarts'
import mapPoint from './modules/map-point'

import {
  getEndTimeOfDay,
  getStartTimeOfDay,
  sortLngLatPointsClockwise,
  sortPolygonPointsClockwise,
  ConvexHull,
  getZeroTimeStampOfDay,
  getEndOfDayTimeStamp,
  getStartDateOfThisWeekWithMoment,
  getEndDateOfThisWeekWithMoment,
  getStartDateOfThisMonth,
  getEndDateOfThisMonth,
} from '../../../utils/util'

import eCharts from '@/components/eCharts/index'
import abnormalData from './modules/abnormalData'
import SettingFence from './modules/settingFence.vue'
import { deviceAnalysis, setResponsiblePerson, wbHttpRestart } from '../../../api/api'
import BindingPersonnel from './modules/bindingPersonnel.vue'
import moment from 'moment'

function generateHeartRate(minDay, maxDay, dataArr = []) {
  var today = new Date()
  var year = today.getFullYear() // 获取当前年份
  var month = today.getMonth() + 1 // 获取当前月份（月份从0开始，所以+1）
  var day = today.getDate() // 获取当前日（号）

  // 格式化日期为 'YYYY-MM-DD' 字符串
  var todayStr = year + '-' + month + '-' + day
  const option = {
    title: {
      text: '心率数据',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#8FBBFF',
      },
    },
    textStyle: {
      color: '#fff',
      fontFamily: 'Source Han Sans',
      fontWeight: 'lighter',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
      formatter: function (params) {
        const v = params[0].value
        return `时间：${v[0]}<br/> 心率值：${v[1]}<br/> `
      },
    },
    grid: {
      top: 50,
      containLabel: true,
      bottom: 50,
      right: 50,
      left: 50,
    },
    xAxis: {
      type: 'time',
      min: getZeroTimeStampOfDay(minDay),
      boundaryGap: true,
      max: getEndOfDayTimeStamp(maxDay),
      axisLine: {
        show: true,
        lineStyle: {
          color: '#0853c7',
        },
      },
      // 坐标轴小标记
      axisTick: {
        show: true,
      },
      // 坐标轴文本标签
      axisLabel: {
        textStyle: {
          color: '#6EA7FF',
        },
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: '#ebeff6',
          // type: 'dashed'
        },
      },
      // 分隔区域
      splitArea: {
        show: false,
      },
    },
    yAxis: {
      // name: '能耗比',
      nameTextStyle: {
        color: '#000',
        fontSize: 10,
        align: 'center',
        padding: [0, 0, 0, 0],
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#0853c7',
        },
      },
      // 坐标轴小标记
      axisTick: {
        show: true,
      },
      // 坐标轴文本标签
      axisLabel: {
        textStyle: {
          color: '#6EA7FF',
        },
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: '#ebeff6',
          // type: 'dashed'
        },
      },
      // 分隔区域
      splitArea: {
        show: false,
      },
    },
    dataZoom: [
      {
        textStyle: {
          color: '#fff',
        },
        // 这个dataZoom组件，默认控制x轴。
        type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
        start: 0, // 左边在 10% 的位置。
        end: 100, // 右边在 60% 的位置。
      },
      {
        // 这个dataZoom组件，也控制x轴。
        type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
        start: 0, // 左边在 10% 的位置。
        end: 100, // 右边在 60% 的位置。
      },
    ],
    series: [
      {
        symbolSize: 6,
        name: 'a',
        data: dataArr,
        color: '#47e829',
        type: 'scatter',
      },
    ],
  }

  return option
}

function genBloodOptions(minDay, maxDay, dataList) {
  function addAlpha(rgb, alpha) {
    // 匹配rgb颜色格式
    const rgbPattern = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/
    const match = rgb.match(rgbPattern)

    if (!match) {
      throw new Error('Invalid RGB format')
    }

    // 提取红、绿、蓝值
    const r = match[1]
    const g = match[2]
    const b = match[3]

    // 返回rgba颜色格式
    return `rgba(${r},${g},${b},${alpha})`
  }

  let colors = ['rgb(150,208,135)', 'rgb(63,162,246)', 'rgb(244,162,97)', 'rgb(145,122,176)']

  let data = {
    data: dataList,
    title: '营造林月份统计',
    legend: ['高压', '低压'],
  }

  let series = data.data.map((item, index) => {
    return {
      name: data.legend[index],
      type: 'line',
      smooth: true, //是否平滑
      showAllSymbol: true,
      symbol: 'circle',
      symbolSize: 10,
      lineStyle: {
        color: colors[index],
      },
      label: {
        show: false,
        position: 'top',
        textStyle: {
          color: colors[index],
        },
      },
      itemStyle: {
        color: colors[index],
        borderColor: '#fff',
        borderWidth: 2,
        shadowColor: 'rgba(0, 0, 0, .1)',
        shadowBlur: 0,
        shadowOffsetY: 2,
        shadowOffsetX: 2,
      },
      tooltip: {
        show: true,
      },
      areaStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1,
            [
              {
                offset: 0,
                color: addAlpha(colors[index], 0.2),
              },
              {
                offset: 1,
                color: addAlpha(colors[index], 0),
              },
            ],
            false
          ),
          shadowColor: 'rgba(0,179,244, 0.5)',
          shadowBlur: 20,
        },
      },
      data: data.data[index],
    }
  })
  let option = {
    title: {
      text: '血压数据',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#8FBBFF',
      },
    },
    textStyle: {
      color: '#fff',
      fontFamily: 'Source Han Sans',
      fontWeight: 'lighter',
    },
    tooltip: {
      show: true,
      trigger: 'axis',
      axisPointer: {
        label: {
          show: true,
        },
      },
    },
    grid: {
      top: 50,
      containLabel: true,
      bottom: 50,
      right: 50,
      left: 50,
    },
    xAxis: [
      {
        type: 'time',
        boundaryGap: true,
        min: getZeroTimeStampOfDay(minDay),
        max: getEndOfDayTimeStamp(maxDay),
        axisLine: {
          show: true,
          lineStyle: {
            color: '#0853c7',
          },
        },
        // 坐标轴小标记
        axisTick: {
          show: true,
        },
        // 坐标轴文本标签
        axisLabel: {
          textStyle: {
            color: '#6EA7FF',
          },
        },
        splitLine: {
          show: false,
          lineStyle: {
            color: '#ebeff6',
            // type: 'dashed'
          },
        },
        // 分隔区域
        splitArea: {
          show: false,
        },
        data: data.xAxis,
      },
    ],
    yAxis: [
      {
        type: 'value',
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: 'rgba(0, 0, 0, 0.15)',
          },
        },
        // 坐标轴线
        axisLine: {
          show: true,
          lineStyle: {
            color: '#0853c7',
          },
        },
        // 坐标轴小标记
        axisTick: {
          show: true,
        },
        // 坐标轴文本标签
        axisLabel: {
          textStyle: {
            color: '#6EA7FF',
          },
        },
        // 分隔线
        splitLine: {
          show: false,
          lineStyle: {
            color: '#ebeff6',
            // type: 'dashed'
          },
        },
        // 分隔区域
        splitArea: {
          show: false,
        },
      },
    ],
    legend: {
      show: true,
      x: 'right',
      y: 'top',
      textStyle: {
        color: '#6EA7FF',
      },
    },
    dataZoom: [
      {
        textStyle: {
          color: '#fff',
        },
        // 这个dataZoom组件，默认控制x轴。
        type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
        start: 0, // 左边在 10% 的位置。
        end: 100, // 右边在 60% 的位置。
      },
      {
        // 这个dataZoom组件，也控制x轴。
        type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
        start: 0, // 左边在 10% 的位置。
        end: 100, // 右边在 60% 的位置。
      },
    ],
    series: series,
  }
  return option
}

function genOxgenOptions(minDay, maxDay, dataList) {
  function addAlpha(rgb, alpha) {
    // 匹配rgb颜色格式
    const rgbPattern = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/
    const match = rgb.match(rgbPattern)

    if (!match) {
      throw new Error('Invalid RGB format')
    }

    // 提取红、绿、蓝值
    const r = match[1]
    const g = match[2]
    const b = match[3]

    // 返回rgba颜色格式
    return `rgba(${r},${g},${b},${alpha})`
  }

  let colors = ['rgb(150,208,135)', 'rgb(63,162,246)', 'rgb(244,162,97)', 'rgb(145,122,176)']

  let data = {
    data: dataList,
    title: '营造林月份统计',
    legend: ['血氧', '低压'],
  }

  let series = data.data.map((item, index) => {
    return {
      name: data.legend[index],
      type: 'line',
      smooth: true, //是否平滑
      showAllSymbol: true,
      symbol: 'circle',
      symbolSize: 10,
      lineStyle: {
        color: colors[index],
      },
      label: {
        show: false,
        position: 'top',
        textStyle: {
          color: colors[index],
        },
      },
      itemStyle: {
        color: colors[index],
        borderColor: '#fff',
        borderWidth: 2,
        shadowColor: 'rgba(0, 0, 0, .1)',
        shadowBlur: 0,
        shadowOffsetY: 2,
        shadowOffsetX: 2,
      },

      tooltip: {
        show: true,
      },
      areaStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1,
            [
              {
                offset: 0,
                color: addAlpha(colors[index], 0.2),
              },
              {
                offset: 1,
                color: addAlpha(colors[index], 0),
              },
            ],
            false
          ),
          shadowColor: 'rgba(0,179,244, 0.5)',
          shadowBlur: 20,
        },
      },
      data: data.data[index],
    }
  })
  let option = {
    title: {
      text: '血氧数据',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#8FBBFF',
      },
    },
    textStyle: {
      color: '#fff',
      fontFamily: 'Source Han Sans',
      fontWeight: 'lighter',
    },
    tooltip: {
      show: true,
      trigger: 'axis',
      axisPointer: {
        label: {
          show: true,
        },
      },
    },
    grid: {
      top: 50,
      containLabel: true,
      bottom: 50,
      right: 50,
      left: 50,
    },
    xAxis: [
      {
        type: 'time',
        boundaryGap: true,
        min: getZeroTimeStampOfDay(minDay),
        max: getEndOfDayTimeStamp(maxDay),
        axisLine: {
          show: true,
          lineStyle: {
            color: '#0853c7',
          },
        },
        // 坐标轴小标记
        axisTick: {
          show: true,
        },
        // 坐标轴文本标签
        axisLabel: {
          textStyle: {
            color: '#6EA7FF',
          },
        },
        splitLine: {
          show: false,
          lineStyle: {
            color: '#ebeff6',
            // type: 'dashed'
          },
        },
        // 分隔区域
        splitArea: {
          show: false,
        },
        data: data.xAxis,
      },
    ],
    yAxis: [
      {
        type: 'value',
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: 'rgba(0, 0, 0, 0.15)',
          },
        },
        // 坐标轴线
        axisLine: {
          show: true,
          lineStyle: {
            color: '#0853c7',
          },
        },
        // 坐标轴小标记
        axisTick: {
          show: true,
        },
        // 坐标轴文本标签
        axisLabel: {
          textStyle: {
            color: '#6EA7FF',
          },
        },
        // 分隔线
        splitLine: {
          show: false,
          lineStyle: {
            color: '#ebeff6',
            // type: 'dashed'
          },
        },
        // 分隔区域
        splitArea: {
          show: false,
        },
      },
    ],
    legend: {
      show: false,
      x: 'right',
      y: 'top',
      textStyle: {
        color: '#6EA7FF',
      },
    },
    dataZoom: [
      {
        textStyle: {
          color: '#fff',
        },
        // 这个dataZoom组件，默认控制x轴。
        type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
        start: 0, // 左边在 10% 的位置。
        end: 100, // 右边在 60% 的位置。
      },
      {
        // 这个dataZoom组件，也控制x轴。
        type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
        start: 0, // 左边在 10% 的位置。
        end: 100, // 右边在 60% 的位置。
      },
    ],
    series: series,
  }
  return option
}

function genStepOptions(minDay, maxDay, dataList) {
  function addAlpha(rgb, alpha) {
    // 匹配rgb颜色格式
    const rgbPattern = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/
    const match = rgb.match(rgbPattern)

    if (!match) {
      throw new Error('Invalid RGB format')
    }

    // 提取红、绿、蓝值
    const r = match[1]
    const g = match[2]
    const b = match[3]

    // 返回rgba颜色格式
    return `rgba(${r},${g},${b},${alpha})`
  }

  let colors = ['rgb(150,208,135)', 'rgb(63,162,246)', 'rgb(244,162,97)', 'rgb(145,122,176)']

  let data = {
    data: dataList,
    title: '营造林月份统计',
    legend: ['步数'],
  }

  let series = data.data.map((item, index) => {
    return {
      name: data.legend[index],
      type: 'line',
      smooth: true, //是否平滑
      showAllSymbol: true,
      symbol: 'circle',
      symbolSize: 10,
      lineStyle: {
        color: colors[index],
      },
      label: {
        show: false,
        position: 'top',
        textStyle: {
          color: colors[index],
        },
      },
      itemStyle: {
        color: colors[index],
        borderColor: '#fff',
        borderWidth: 2,
        shadowColor: 'rgba(0, 0, 0, .1)',
        shadowBlur: 0,
        shadowOffsetY: 2,
        shadowOffsetX: 2,
      },
      tooltip: {
        show: true,
      },
      areaStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1,
            [
              {
                offset: 0,
                color: addAlpha(colors[index], 0.2),
              },
              {
                offset: 1,
                color: addAlpha(colors[index], 0),
              },
            ],
            false
          ),
          shadowColor: 'rgba(0,179,244, 0.5)',
          shadowBlur: 20,
        },
      },
      data: data.data[index],
    }
  })
  let option = {
    title: {
      text: '步数统计',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#8FBBFF',
      },
    },
    textStyle: {
      color: '#fff',
      fontFamily: 'Source Han Sans',
      fontWeight: 'lighter',
    },
    tooltip: {
      show: true,
      trigger: 'axis',
      axisPointer: {
        label: {
          show: true,
        },
      },
    },
    grid: {
      top: 50,
      containLabel: true,
      bottom: 50,
      right: 50,
      left: 50,
    },
    xAxis: [
      {
        type: 'time',
        boundaryGap: true,
        min: getZeroTimeStampOfDay(minDay),
        max: getEndOfDayTimeStamp(maxDay),
        axisLine: {
          show: true,
          lineStyle: {
            color: '#0853c7',
          },
        },
        // 坐标轴小标记
        axisTick: {
          show: true,
        },
        // 坐标轴文本标签
        axisLabel: {
          textStyle: {
            color: '#6EA7FF',
          },
        },
        splitLine: {
          show: false,
          lineStyle: {
            color: '#ebeff6',
            // type: 'dashed'
          },
        },
        // 分隔区域
        splitArea: {
          show: false,
        },
        data: data.xAxis,
      },
    ],
    yAxis: [
      {
        type: 'value',
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: 'rgba(0, 0, 0, 0.15)',
          },
        },
        // 坐标轴线
        axisLine: {
          show: true,
          lineStyle: {
            color: '#0853c7',
          },
        },
        // 坐标轴小标记
        axisTick: {
          show: true,
        },
        // 坐标轴文本标签
        axisLabel: {
          textStyle: {
            color: '#6EA7FF',
          },
        },
        // 分隔线
        splitLine: {
          show: false,
          lineStyle: {
            color: '#ebeff6',
            // type: 'dashed'
          },
        },
        // 分隔区域
        splitArea: {
          show: false,
        },
      },
    ],
    legend: {
      show: false,
      x: 'right',
      y: 'top',
      textStyle: {
        color: '#6EA7FF',
      },
    },
    dataZoom: [
      {
        textStyle: {
          color: '#fff',
        },
        // 这个dataZoom组件，默认控制x轴。
        type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
        start: 0, // 左边在 10% 的位置。
        end: 100, // 右边在 60% 的位置。
      },
      {
        // 这个dataZoom组件，也控制x轴。
        type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
        start: 0, // 左边在 10% 的位置。
        end: 100, // 右边在 60% 的位置。
      },
    ],
    series: series,
  }
  return option
}

export default {
  name: 'pringing',
  components: {
    leftTree,
    topTitle,
    list,
    Add,
    CallLogList,
    startEndTime,
    eCharts,
    abnormalData,
    SettingFence,
    BindingPersonnel,
    mapPoint,
  },
  data() {
    return {
      content: [[], []],
      activeKey: 0,
      key: '',
      selectedKey: '',
      addRef: null,
      tabList: [
        {
          title: '基础信息',
        },
        {
          title: '关怀号码',
        },
        // {
        //   title: '提醒管理',
        // },
        // {
        //   title: '修改配置',
        // },
        {
          title: '查看轨迹',
        },
        {
          title: '通话记录',
        },
      ],
      detail: {},
      columns: [
        {
          title: '序号',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '人员姓名',
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: '身份证号码',
          align: 'center',
          dataIndex: 'idCard',
          ellipsis: true,
        },
        {
          title: '所属医疗机构',
          align: 'center',
          dataIndex: 'responsibleOrganization',
          ellipsis: true,
        },
        {
          title: '所属责任区',
          align: 'center',
          dataIndex: 'policeJurisdictionName',
          ellipsis: true,
        },
        {
          title: '爱心关怀人员',
          align: 'center',
          dataIndex: 'helpCount',
          ellipsis: true,
        },
        {
          title: '添加人',
          align: 'center',
          dataIndex: 'createBy',
          ellipsis: true,
        },
        {
          title: '绑定时间',
          align: 'center',
          dataIndex: 'createTime',
          ellipsis: true,
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
          ellipsis: true,
          align: 'center',
          width: 100,
          fixed: 'right',
        },
      ],
      wearingPersonnelList: [],
      abnormalDataColumns: [
        {
          title: '序号',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '类型',
          align: 'center',
          dataIndex: 'type',
          customRender: function (t, r, index) {
            const typeMap = {
              1: 'SOS',
              4: '电子围栏触发',
              8: '运动心率异常',
            }
            return typeMap[t] ? typeMap[t] : ''
          },
        },
        {
          title: '发生时间',
          align: 'center',
          dataIndex: 'eventTime',
          ellipsis: true,
        },
        {
          title: '发生地点',
          align: 'center',
          dataIndex: 'address',
          ellipsis: true,
        },
      ],
      careColumns: [
        {
          title: '序号',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '人员类型',
          align: 'center',
          dataIndex: 'helpPersonType',
        },
        {
          title: '人员姓名',
          align: 'center',
          dataIndex: 'helpName',
          ellipsis: true,
        },
        {
          title: '身份证号码',
          align: 'center',
          dataIndex: 'helpIdCard',
          ellipsis: true,
        },
        {
          title: '手机号码',
          align: 'center',
          dataIndex: 'helpPhone',
          ellipsis: true,
        },
        {
          title: '设为主要负责人 ',
          align: 'center',
          dataIndex: 'isResponsible',
          scopedSlots: { customRender: 'isResponsible' },
          ellipsis: true,
        },
        {
          title: '居住地址/所属单位',
          align: 'center',
          dataIndex: 'orgName',
          ellipsis: true,
        },
        {
          title: '是否下发',
          align: 'center',
          dataIndex: 'issuedStatus',
          customRender(t) {
            return t == 1 ? '已下发' : '未下发'
          },
          ellipsis: true,
        },
        {
          title: '添加人',
          align: 'center',
          dataIndex: 'createBy',
          ellipsis: true,
        },
        {
          title: '添加时间',
          align: 'center',
          dataIndex: 'createTime',
          ellipsis: true,
        },
      ],
      timeType: 'day',
      map: null,
      markerList: [],
      drawing: false,
      ploygonList: [],
      wbDeviceBean: {},
      times: {},
      resetTime: false,
      trackMarkerList: [],
      deviceHelpInfoNumList: [],
      heartRateOptions: {},
      bloodOptions: {},
      oxgenOptions: {},
      stepOptions: {},
      wbMentalPatientBean: [],
      wbEventDataListBean: [],
      settingFenceRef: null,
      point: [],
      searchTime: [],
      fenceInfo: {},
      bindingPersonnelRef: null,
      trackTimeParams: {},
      startEndTimeRef: null,
      mapPointRef: null,
    }
  },
  provide() {
    return {
      provideData: () => {
        return {
          institution: {
            id: this.$route.query.policeAgencyId,
          },
        }
      },
    }
  },
  mounted() {
    this.activeKey = this.$route.query.activeKey ? this.$route.query.activeKey : 0
    // this.initMap()
    this.initData()
    const startValue = this.$moment(getStartTimeOfDay()).format('YYYY-MM-DD HH:mm:ss')
    const endValue = this.$moment(getEndTimeOfDay()).format('YYYY-MM-DD HH:mm:ss')
    this.$refs.startEndTimeRef.startValue = startValue
    this.$refs.startEndTimeRef.endValue = endValue
    this.trackTimeParams.startTime = startValue
    this.trackTimeParams.endTime = endValue
  },
  methods: {
    initData() {
      let params = {
        id: this.$route.query.id,
      }
      deviceDetails(params).then((res) => {
        const { wbDeviceBean, wearingPersonnelList = [], wbMentalPatientBean, wbEventDataListBean } = res.result
        this.wbDeviceBean = wbDeviceBean
        this.wearingPersonnelList = wearingPersonnelList
        this.wbMentalPatientBean = [wbMentalPatientBean]
        this.wbEventDataListBean = wbEventDataListBean
        this.content = [['设备列表'], [`设备详情（${wbDeviceBean.imei}）`]]
        this.getFence()
        const parmas = {
          deviceImei: this.wbDeviceBean.imei,
          type: 0,
          startTime: moment().valueOf(),
          endTime: moment().valueOf(),
          analysisType: 0,
        }
        this.getDeviceData(parmas)
      })
      this.getHelpInfo()
    },
    getHelpInfo() {
      if (this.$route.query.psychopathId) {
        deviceHelpInfoList({
          id: this.$route.query.psychopathId,
        }).then((res) => {
          this.deviceHelpInfoNumList = res.result.map((item) => {
            return {
              ...item,
              status: item.isResponsible == '1' ? true : false,
            }
          })
        })
      }
    },
    handelClick(event) {
      this.activeKey = event
      this.searchTableData()
    },
    searchTableData() {
      this.$nextTick(() => {
        // 调用各个组件的 search 方法
        this.$refs.listRef.searchQuery()
      })
    },
    handelAdd() {
      this.$refs.addRef.show()
    },
    handleChange(records) {
      const params = {
        id: this.wbDeviceBean.id,
      }
      this.$refs.bindingPersonnelRef.show(params)
    },
    onEditOk() {
      // this.initMap()
      this.initData()
    },
    onChange() {},
    initMap() {
      this.map = new AMap.Map('map-box', {
        resizeEnable: true,
        center: [116.397428, 39.90923],
        zoom: 13,
      })
      this.map.on('click', (e) => {
        if (!this.drawing) {
          return
        }
        const position = [e.lnglat.lng, e.lnglat.lat]
        //如果没有 marker 则添加 ，否则新增
        this.addMarker(this.map, position, this.markerList)
      })

      //输入提示
      var autoOptions = {
        input: 'tipinput',
      }
      var auto = new AMap.Autocomplete(autoOptions)
      var placeSearch = new AMap.PlaceSearch({
        map: this.map,
      }) //构造地点查询类
      AMap.event.addListener(auto, 'select', select) //注册监听，当选中某条记录时会触发
      function select(e) {
        placeSearch.setCity(e.poi.adcode)
        placeSearch.search(e.poi.name) //关键字查询查询
      }
    },
    addMarker(map, position, list, item) {
      var marker = new AMap.Marker({
        position: position,
        icon: new AMap.Icon({
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
          size: new AMap.Size(25, 34),
          imageSize: new AMap.Size(25, 34), //图标大小
        }),
        anchor: 'bottom-center',
        offset: new AMap.Pixel(0, 0),
      })

      marker.setMap(map)

      // 设置鼠标划过点标记显示的文字提示
      if (item) {
        marker.setTitle(item.address)
      } else {
        marker.setTitle('')
      }

      // 设置label标签
      // label默认蓝框白底左上角显示，样式className为：amap-marker-label
      if (item) {
        marker.setLabel({
          direction: 'top',
          offset: new AMap.Pixel(0, 0), //设置文本标注偏移量
          content: `<div class='info'>${list.length + 1}：${item.createTime}</div>`, //设置文本标注内容
        })
      } else {
        marker.setLabel({
          direction: 'top',
          offset: new AMap.Pixel(0, 0), //设置文本标注偏移量
          content: `<div class='info'>点${list.length + 1}</div>`, //设置文本标注内容
        })
      }
      list.push(marker)
    },
    // 开启鼠标绘制
    handleStartMouse() {
      this.drawing = true
    },
    // 四个点确定
    handleConfirmPoint() {
      if (this.markerList.length > 4) {
        this.$message.warning('绘制点数量不能超过4个！')
        return
      }
      if (this.markerList.length < 4) {
        this.$message.warning('请先绘制点！')
        return
      }
      let ploygonList = this.markerList.map((item) => {
        let tempItem = item.getPosition()
        return {
          ...tempItem,
          x: tempItem.lat,
          y: tempItem.lng,
        }
      })

      // 凸包处理精度的
      ploygonList = ConvexHull(ploygonList)
      let pos = ploygonList.reduce((acc, curr, index) => {
        acc[`pos${index + 1}Lon`] = curr.lng
        acc[`pos${index + 1}Lat`] = curr.lat
        return acc
      }, {})

      if (!ploygonList.length) {
        return
      }

      wbHttpFences({
        freq: 1,
        timeBegin: '00:00',
        timeEnd: '24:00',
        type: 0,
        enable: 1,
        deviceId: this.wbDeviceBean.id,
        imei: this.wbDeviceBean.imei,
        ...pos,
      }).then((res) => {
        this.$message.success('设置成功!')
      })
      this.addPloygon(ploygonList)
    },
    // 清除所有点
    handleClearPoint() {
      this.markerList.forEach((marker) => {
        marker.setMap(null)
      })
      this.markerList = []

      // 顺便移除之前的覆盖物
      this.ploygonList.forEach((ploygonInstance) => {
        this.map.remove(ploygonInstance)
      })
    },

    // 添加覆盖物
    addPloygon(polygonPath) {
      // 先移除
      this.ploygonList.forEach((ploygonInstance) => {
        this.map.remove(ploygonInstance)
      })
      this.ploygonList = []
      const points = polygonPath.map((item) => {
        return [item.lng, item.lat]
      })
      var polygon = new AMap.Polygon({
        path: sortPolygonPointsClockwise(points),
      })
      this.ploygonList.push(polygon)
      this.map.add([polygon])
    },
    timeChange(v, index) {
      if (index == 1) {
        this.trackTimeParams.startTime = this.$moment(v).valueOf()
        if (v == null) {
          this.trackTimeParams.startTime = null
        }
      } else {
        this.trackTimeParams.endTime = this.$moment(v).valueOf()
        if (v == null) {
          this.trackTimeParams.endTime = null
        }
      }
    },
    searchReset() {
      const startValue = this.$moment(getStartTimeOfDay()).format('YYYY-MM-DD HH:mm:ss')
      const endValue = this.$moment(getEndTimeOfDay()).format('YYYY-MM-DD HH:mm:ss')
      this.$refs.startEndTimeRef.startValue = startValue
      this.$refs.startEndTimeRef.endValue = endValue
      this.trackTimeParams.startTime = getStartTimeOfDay()
      this.trackTimeParams.endTime = getEndTimeOfDay()
      this.searchQueryTrack()
    },
    drawingTrack(params) {
      this.map.remove(this.trackMarkerList)
      this.trackMarkerList = []
      deviceTrajectory(params).then((res) => {
        let paths = []
        res.result.forEach((item) => {
          const position = [item.lon, item.lat]
          paths.push(position)
          this.addMarker(this.map, position, this.trackMarkerList, item)
        })
        console.log(this.trackMarkerList)
        // 绘制线条
        var polyline = new AMap.Polyline({
          path: paths,
          strokeColor: '#3366FF',
          strokeWeight: 2,
          strokeOpacity: 1,
          strokeStyle: 'solid',
          strokeDasharray: [10, 5],
          lineJoin: 'round',
        })
        polyline.setMap(this.map)
        this.map.setFitView()
      })
    },
    handleTabsChange(v) {
      if (v == 2) {
        const params = {
          imei: this.wbDeviceBean.imei,
          startTime: getStartTimeOfDay(),
          endTime: getEndTimeOfDay(),
        }
        this.drawingTrack(params)
      }
    },

    getFence() {
      deviceinfoSetFance({
        imei: this.wbDeviceBean.imei,
      }).then((res) => {
        // 判断是否有结果
        if (!res.result) {
          this.$message.warning('未获取到围栏信息！')
          return
        }
        // 先清除在绘制
        const result = res.result
        this.fenceInfo = {
          ...result,
        }
        let path = [
          { lat: result.pos1Lat, lng: result.pos1Lon },
          { lat: result.pos2Lat, lng: result.pos2Lon },
          { lat: result.pos3Lat, lng: result.pos3Lon },
          { lat: result.pos4Lat, lng: result.pos4Lon },
        ]
        this.point = path
        this.addPloygon(path)
      })
    },
    handleSettingFence() {
      this.$refs.settingFenceRef.show()
    },
    onSetFence() {
      this.getFence()
    },
    getDeviceData(params) {
      // 获取 设备数据
      deviceAnalysis({
        ...params,
        analysisType: 0,
      }).then((res) => {
        // 获取到数据拼接数据
        let x = Object.keys(res.result.dataMap)
        let dataList = res.result.dataMap
        let data = Object.keys(dataList).map((key) => {
          return [key, dataList[key]]
        })
        let minDay = params.startTime
        let maxDay = params.endTime
        this.heartRateOptions = generateHeartRate(minDay, maxDay, data)
      })
      deviceAnalysis({
        ...params,
        analysisType: 1,
      }).then((res) => {
        // 获取到数据拼接数据
        // 低压
        let x = Object.keys(res.result.dbpMap)
        const { dbpMap, sbpMap } = res.result
        let data = [
          Object.keys(dbpMap).map((key) => {
            return [key, dbpMap[key]]
          }),
          Object.keys(sbpMap).map((key) => {
            return [key, sbpMap[key]]
          }),
        ]
        console.log(data)
        let minDay = params.startTime
        let maxDay = params.endTime
        this.bloodOptions = genBloodOptions(minDay, maxDay, data)
      })
      deviceAnalysis({
        ...params,
        analysisType: 2,
      }).then((res) => {
        // 获取到数据拼接数据
        let dataList = res.result.dataMap
        let data = Object.keys(dataList).map((key) => {
          return [key, dataList[key]]
        })
        let minDay = params.startTime
        let maxDay = params.endTime
        this.oxgenOptions = genOxgenOptions(minDay, maxDay, [data])
      })
      deviceAnalysis({
        ...params,
        analysisType: 3,
      }).then((res) => {
        // 获取到数据拼接数据
        let x = Object.keys(res.result.dataMap)
        let minDay = params.startTime
        let maxDay = params.endTime
        let dataList = res.result.dataMap
        let data = Object.keys(dataList).map((key) => {
          return [key, dataList[key]]
        })
        this.stepOptions = genStepOptions(minDay, maxDay, [data])
      })
    },
    handleTimeTypeChange(value) {
      this.searchTime = []
      const dayMap = {
        day: 0,
        week: 1,
        month: 2,
      }
      // 根据时间分别获取时间段
      const val = value.target.value
      //  计算开始时间
      let startTime = ''
      let endTime = ''
      if (val == 'day') {
        startTime = moment().valueOf()
        endTime = moment().valueOf()
      } else if (val == 'week') {
        startTime = getStartDateOfThisWeekWithMoment()
        endTime = getEndDateOfThisWeekWithMoment()
      } else if (val == 'month') {
        startTime = getStartDateOfThisMonth()
        endTime = getEndDateOfThisMonth()
      }

      // 和结束时间
      this.getDeviceData({
        deviceImei: this.wbDeviceBean.imei,
        type: dayMap[val],
        startTime: startTime,
        endTime: endTime,
        analysisType: 0,
      })
    },
    handleTimeRange() {
      const start = this.searchTime[0]
      const end = this.searchTime[1]
      const parmas = {
        deviceImei: this.wbDeviceBean.imei,
        type: 3,
        startTime: moment(start).format('YYYY-MM-DD'),
        endTime: moment(end).format('YYYY-MM-DD'),
        analysisType: 0,
      }
      this.getDeviceData(parmas)
    },
    handleReset() {
      wbHttpRestart({
        imei: this.wbDeviceBean.imei,
      }).then((res) => {
        if (res.code == 200) {
          this.$message.success('操作成功！')
          this.initData()
        }
      })
    },
    handleChangeResponsible(records) {
      setResponsiblePerson({
        helpId: records.id,
        mentalPatientPersonId: this.wbDeviceBean.psychopathId,
      })
        .then((res) => {
          this.$message.success(res.message)
          if (res.code == 200) {
            this.getHelpInfo()
          }
        })
        .catch(() => {
          // records.status = false
        })
    },
    searchQueryTrack() {
      const { startTime, endTime } = this.trackTimeParams
      if ((startTime && !endTime) || (!startTime && endTime)) {
        this.$message.error('开始时间结束时间必须同时选择')
        return
      }
      const params = {
        imei: this.wbDeviceBean.imei,
        startTime: startTime,
        endTime: endTime,
      }
      this.drawingTrack(params)
    },
    showPosition(position) {
      this.$refs.mapPointRef.show(position)
    },
  },
}
</script>
<style>
.amap-sug-result {
  display: none; /* 如果确定不需要显示自动完成的结果，可以隐藏 */
}
</style>

<style lang="less" scoped>
.online-status {
  position: relative;
  &::before {
    content: '';
    width: 6px;
    display: block;
    height: 6px;
    background: #47e829;
    border-radius: 50%;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 10px;
  }
}
.offline-status {
  position: relative;
  &::before {
    content: '';
    width: 6px;
    display: block;
    left: 10px;
    height: 6px;
    background: #abd5ff;
    border-radius: 50%;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
  }
}

.visitor-index {
  width: 100%;
  height: 100%;
  .pageInfo {
    width: 100%;
    height: 100%;
    display: flex;
    .tab-info {
      width: 160px;
      height: 100%;
      background: var(--theme-container-bg);
      border-radius: 4px 4px 4px 4px;
      padding-top: 23px;
      margin-right: 8px;
      flex-shrink: 0;
      /deep/ .ant-tabs-bar {
        width: 100%;
        border-right: 0;
      }
      /deep/ .ant-tabs-tab-active {
        font-weight: 500 !important;
        font-size: 14px !important;
        color: #ffffff !important;
      }
      /deep/ .ant-tabs-tab {
        text-align: center;
        font-weight: 400;
        font-size: 14px;
        color: #abd5ff;
      }
      /deep/ .ant-tabs-left-bar {
        .ant-tabs-ink-bar {
          width: 0;
        }
      }
    }
    .right-content {
      flex: 1;
      background: var(--theme-container-bg);
      padding: 21px 24px;
      overflow: auto;
      .common-title {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        margin-top: 12px;

        .icon {
          width: 6px;
          height: 6px;
          background: #abd5ff;
          border-radius: 50%;
          margin-right: 7px;
        }
        .content {
          font-weight: 500;
          font-size: 14px;
          color: var(--theme-tab-text-color);
        }
      }

      .wearing-table {
        /deep/.ant-table-thead > tr > th {
          height: 46px;
          background: #0946a8;
          border-radius: 0px 0px 0px 0px;
          border: 1px solid #0855cc;
          font-weight: 500;
          font-size: 14px;
          color: #8fbbff;
          border-right: 0;
          &:last-child {
            border-right: 1px solid #0855cc;
          }
        }
        /deep/ .ant-table-thead {
          border-right: 1px solid #0855cc;
        }
        /deep/ .ant-table-tbody .ant-table-row td {
          background: #07429e;
          border-radius: 0px 0px 0px 0px;
          border: 1px solid #0855cc;
          color: #ffffff;
          border-right: 0;
          border-top: 0;
        }

        /deep/.ant-table-placeholder {
          background-color: var(--theme-container-bg);
          border: 1px solid #0855cc;
          border-top: 0;
          .ant-empty-normal {
            color: #fff;
          }
        }
      }
      .content-wrapper {
        border-top: 1px solid #0855cc;
        border-left: 1px solid #0855cc;

        .info-wrap {
          display: flex;
          align-items: stretch;
          border-bottom: 1px solid #0855cc;
          border-right: 1px solid #0855cc;
          position: relative;

          .label {
            background: #0946a8;
            width: 160px;
            padding: 14px 20px;
            font-weight: 500;
            font-size: 14px;
            color: #8fbbff;
            border-right: 1px solid #0855cc;
          }
          .value {
            font-weight: 400;
            font-size: 14px;
            color: #ffffff;
            padding: 14px 20px;
          }
          .location-icon-style {
            width: 19px;
            height: 19px;
            margin-left: 4px;
            cursor: pointer;
          }
          .refresh-box {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            right: 10px;
            color: #34ff0f;
          }
        }
      }

      .time-select {
        display: flex;
        .time-btn-style {
          .ant-radio-button-wrapper {
            background: #06409a;
            border: 1px solid #0855cc;
            font-weight: 500;
            font-size: 14px;
            color: #8fbbff;
            &::before {
              width: 0;
            }
          }
          .ant-radio-button-wrapper-checked {
            background: #1970f6;
            border: 1px solid #1970f6;
          }
        }
        .time-range {
          width: 310px !important;
          margin-left: 8px;
        }
      }
    }
  }
  .title-wrapper-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .l-w_content {
    margin-left: 2px;
  }
  .right-inner-box {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    .map-wrapper {
      flex: 1;
    }
    #map-box {
      width: 100%;
      height: 100%;
    }
    .button-group {
      position: absolute;
      right: 10px;
      z-index: 10;
      padding-top: 6px;
      .i-btn {
        margin-right: 6px;
      }
    }
  }
}
</style>
